package xyz.liuz.netty.thirdexample;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

public class MyChatServerHandler extends SimpleChannelInboundHandler<String> {
    //ChannelGroup保存channel对象
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    //服务器端收到客户点消息后调用
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.forEach(ch -> {
            System.out.println(ch.remoteAddress()+"---------------");
            if(channel != ch){

                ch.writeAndFlush(channel.remoteAddress()+"message sent:"+msg+"\n");
            }else{
                ch.writeAndFlush("[oneself]-"+msg+"\n");
            }
        });
    }
    //连接建立
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        //写入组的所有的channel-发送通知
        channelGroup.writeAndFlush("[SERVER]-"+channel.remoteAddress()+"join\n");
        //将新的channel加入组
        channelGroup.add(channel);
    }

    //连接断开
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.writeAndFlush("[SERVER]-"+channel.remoteAddress()+"leave\n");
        //连接断开会自动移除，无需手动移除
        //channelGroup.remove(channel);
    }
    //连接处于活动状态
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println(channel.remoteAddress()+"上线");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println(channel.remoteAddress()+"offline");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
